package neu.edu.cn.nuemall.config;

import neu.edu.cn.nuemall.service.PublishService;
import neu.edu.cn.nuemall.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.UserDetails;

import javax.servlet.http.HttpSession;

@Configuration
public class ApplicationUserLoginListener implements ApplicationListener {

    @Autowired
    private HttpSession session;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private PublishService publishService;

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof AuthenticationSuccessEvent){
            //监听spring security 登录成功事件，将用户信息写入到session中
            AuthenticationSuccessEvent loginSuccessEvent=(AuthenticationSuccessEvent) event;
            UserDetails userDetails=(UserDetails) loginSuccessEvent.getAuthentication().getPrincipal();
            session.setAttribute("USER_INFO",userinfoService.getUserByName(userDetails.getUsername()));
        }
    }
}
